package no.cicero.testframework.xml;

import no.cicero.testframework.common.xml.XmlImporter;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.IOException;
import java.io.InputStream;

public class XmlImporterValidation extends XmlImporter {
    private String schemaFile;

    public XmlImporterValidation(SAXParser p, String schemaFile) {
        super(p);
        this.schemaFile = schemaFile;
    }

    public void validateStream(InputStream is) throws SAXException, IOException {
        InputStream schemaStream = getClass().getClassLoader().getResourceAsStream(schemaFile);
        assert schemaStream != null : "XML schema not found";
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
        schema.newValidator().validate(new StreamSource(is));
    }

}
